package com.bb.blog.web.component;

import com.alibaba.fastjson.JSONObject;
import com.bb.blog.web.constant.CommonServerExceptionEnum;
import com.bb.blog.web.model.CommonResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ResponseUtil {

    /**
     * 构造Response
     */
    public static <T> CommonResponse<T> success(T data) {
        return new CommonResponse<>(HttpStatus.OK, data);
    }


    public static <T> CommonResponse<T> fail(HttpStatus httpStatus, T msg) {
        return new CommonResponse<>(httpStatus, msg);
    }

    public static <T> CommonResponse<T> fail(int code, String msg, T data) {
        return new CommonResponse<>(code, msg, data);
    }
    public static  CommonResponse fail(CommonServerExceptionEnum exceptionEnum){
        return new CommonResponse<>(exceptionEnum.getCode(), exceptionEnum.getMsg(), exceptionEnum.getData());
    }


    public static <T> CommonResponse<T> redirect(int code, String msg, T data) {
        return new CommonResponse<>(HttpStatus.FOUND, data);
    }

    /**
     * 处理 ServletResponse
     */
    public static void parseResponse(HttpServletResponse response, CommonResponse commonResponse) {
        String jsonResponse = JSONObject.toJSONString(commonResponse);
        response.setStatus(commonResponse.getCode());
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        try {
            response.getWriter().write(jsonResponse);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
